﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

namespace WebTest.Tool
{
    public static class JsonHelper
    {
        /// <summary>
        /// 将实体和列表转为JSON对象
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson(this object obj)
        {
            JavaScriptSerializer serializer=new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }

        /// <summary>
        /// 将列表元素转成JSON对象
        /// </summary>
        /// <typeparam name="T">元素类型</typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string ListToJson<T>(IList<T> t)
        {
            StringBuilder Json = new StringBuilder();
            Json.Append("[");
            if (t.Count > 0)
            {
                for (int i = 0; i < t.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    Type type = obj.GetType();
                    PropertyInfo[] pis = type.GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pis.Length; j++)
                    {
                        Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + pis[j].GetValue(t[i], null) + "\"");
                        if (j < pis.Length - 1)
                        {
                            Json.Append(",");
                        }
                        else
                        {
                            Json.Append("}");
                        }
                    }
                    if (i < t.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]");
            return Json.ToString();
        }
    }
}
